package cc.linker.steplink.crm.support.oauth;

import cc.linker.steplink.crm.commons.RedisConstants;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.lock.RedisLock;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 获取access_token
 */
@Slf4j
public class GetOrRefreshToken {

    private final static String CONTENT_TYPE = "application/x-www-form-urlencoded";
    private final static String CREDEBTIALS_BASIC = "Basic ";
    private final static String AUTH_BEARER = "bearer ";
    
    @Autowired
    private HttpService httpService;
    @Autowired
    private OauthProperties oauthProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RedisLock("SendWxMessage_SendMassMsg")
    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/10 * * * * ?")
    public void refresh() {
        Long expire = stringRedisTemplate.getExpire(RedisConstants.CRM_OAUTH_ACCESS_TOKEN);
        if (expire != null && expire > 300L) {
            // access_token未过期
            return;
        }
        String clientId = oauthProperties.getClientId();
        String clientSecret = oauthProperties.getClientSecret();
        
        String basicScheme = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
        
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credentials");
        params.put("client_id", oauthProperties.getClientId());

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", CONTENT_TYPE);
        headers.put("Authorization", CREDEBTIALS_BASIC + basicScheme);

        try {
            String body = httpService.doPost(oauthProperties.getServerUrl()+"accessToken",params,headers);
//            String body = "{\n" +
//                    "    \"access_token\": \"AT-5-v5eFtGZoUNROkbEE7wpGrm30AYNg05Ri\",\n" +
//                    "    \"token_type\": \"bearer\",\n" +
//                    "    \"expires_in\": 7200,\n" +
//                    "    \"refresh_token\": \"RT-4-LtalvqY7na7gkvUYilaCOWsrJZ-wM-Ho\"\n" +
//                    "}";
            if (!StringUtils.isEmpty(body)) {// redis存储
                TokenResponse tokenResponse = JSON.parseObject(body, TokenResponse.class);
                if (!StringUtils.isEmpty(tokenResponse.getAccessToken())) {
                    stringRedisTemplate.opsForValue().set(RedisConstants.CRM_OAUTH_ACCESS_TOKEN,
                            tokenResponse.getAccessToken(), tokenResponse.getExpiresIn(), TimeUnit.SECONDS);
                } else {
                    return;
                }
                if (!StringUtils.isEmpty(tokenResponse.getRefreshToken())) {
                    stringRedisTemplate.opsForValue().set(RedisConstants.CRM_OAUTH_REFRESH_TOKEN,
                            tokenResponse.getRefreshToken());
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
